import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    ScrollView,
    TouchableOpacity,
    TextInput,
    ListView,
    Modal,
    Animated,
    Platform,
    TouchableNativeFeedback,
    TouchableHighlight,
    InteractionManager
} from 'react-native';
import ImageWrapper from '../components/ImageWrapper';
import StorageUser from '../lib/plugins/StorageUser';
import NavigationBar from '../components/NavigationBar';
import { SwipeListView,SwipeRow } from 'react-native-swipe-list-view';
import shopService from '../lib/services/shopService';
var Dimensions = require('Dimensions');
const { width, height } = Dimensions.get('window');
export default class CardList extends Component{
    constructor(props) {
        super(props);
        this.token = '';
        this.userId = '';
        this.cardList = [];
        var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.state = {
            dataSource:ds.cloneWithRows(this.cardList),
            index:0,
        };
        
    }
    componentDidMount() {
        var $this = this;
        StorageUser._getUser()
            .then(data=>{
                if(data.token){
                    $this.token = data.token;
                }
                if(data.userId){
                    $this.userId = data.userId;
                }
                InteractionManager.runAfterInteractions(() => {
                    $this.getCardList();
                });            
            }).catch(err=> {
                console.log(err)
            });
    }
    
    render(){
        return (
            <View style={styles.container}>
                <NavigationBar 
                    leftIcon={'left'} 
                    titleText={'银行卡列表'} 
                    leftPress={()=>this.goBack()}/>
                <ScrollView>
                    <SwipeListView
                        dataSource={this.state.dataSource}
                        enableEmptySections={true}
                        closeOnRowBeginSwipe={true}
                        rightOpenValue={-70} 
                        disableRightSwipe={true}
                        renderRow={(data, secdId, rowId, rowMap) => (
                            <TouchableHighlight underlayColor={'#fff'}  onPress={ ()=> {rowMap[`${secdId}${rowId}`].closeRow()}}>
                                <View>
                                    <CardItem bankName={data.card_type.split('-')[0]} bankStaturs={data.card_type.split('-')[data.card_type.split('-').length-1]} bankNum={data.card_num}/>
                                </View>
                            </TouchableHighlight>
                        )}
                        renderHiddenRow={ (data, secdId, rowId) => (
                            <View style={{flex:1,flexDirection:'row',justifyContent:'flex-end'}}>
                                <TouchableOpacity onPress={()=>this.deleteCards(data,rowId)} style={{backgroundColor:'#ff0000',width:70,alignItems:'center',justifyContent:'center'}}>
                                    <View>
                                        <Text style={{color:'#fff',fontSize:16}}>删除</Text>
                                    </View>
                                </TouchableOpacity>
                            </View>
                    )}/>
                    <TouchableOpacity onPress={()=>this.goBankCard()}>
                        <View style={styles.addBtn}>
                            <Text style={{fontSize:24,marginTop:-5,color:'#fff'}}>+</Text>
                            <Text style={{flex:1,fontSize:16,color:'#fff'}}>添加银行卡</Text>
                            <ImageWrapper icon={'right'} style={{tintColor:'#fff'}}/>
                        </View>
                    </TouchableOpacity>
                </ScrollView>
                
            </View>
        )
    }
    // 返回按钮
    goBack(){
        this.props.navigation.goBack();
    }
    goBankCard(){
        var $this = this;
        const {navigate } = this.props.navigation;
        navigate('BankCard',{upData:()=>{
            $this.getCardList();
        }})
    }
    // 选择银行
    async selectItem(item,index){
        await this.setState({
            index:index
        })
        this.props.navigation.state.params.upData(item);
        this.goBack();
    }
    // 取消绑定银行卡
    deleteCards(item,index){
        // console.log(111);
        // alert(item.card_id+'---'+this.token)
        var $this = this;
        this.cardList.splice(index,1);
        shopService.bankInfoDel(function(data){
            // alert(JSON.stringify(data));
            if(data.code==10000){
                $this.cardList = JSON.parse(JSON.stringify($this.cardList));
                $this.setState({
                    dataSource:$this.state.dataSource.cloneWithRows($this.cardList)
                })
            }
        },item.card_id,$this.token)
    }
    // 获取银行卡列表
    getCardList(){
        var $this = this;
        shopService.userBindBankLists(function(data){
            // alert(JSON.stringify(data));
            if(data.code==10000){
                $this.cardList = data.data;
                $this.setState({
                    dataSource:$this.state.dataSource.cloneWithRows($this.cardList)
                })
            }
        },$this.userId,$this.token)
    }


}

class CardItem extends Component{
    render(){
        var select = this.props.select;
        var number = this.props.bankNum;
        var num = number.slice(-4);
        return(
            <View style={styles.itemBox}>
                <View style={styles.leftBox}>
                    <Text style={{color:'#333',fontSize:16}}>{this.props.bankName}</Text>
                    <Text style={{fontSize:14}}>{this.props.bankStaturs}</Text>
                </View>
                <View style={styles.numberBox}>
                    <Text style={{color:'rgb(79,145,237)',fontSize:30}}>**** **** ****</Text>
                    <Text style={{color:'rgb(79,145,237)',fontSize:20}}> {num}</Text>
                </View>
            </View>
        )
    }
}
const styles = StyleSheet.create({
    container:{
        flex:1,
        backgroundColor:'#EFEFF4',
        ...Platform.select({
            ios: {
                marginTop: 20
            },
            android: {
                marginTop:0
            },
        }),
    },
    itemBox:{
        backgroundColor:'#fff',
        paddingTop:5,
        height:90,
        paddingLeft:10,
        paddingRight:10,
        borderBottomWidth:1,
        borderBottomColor:'#ccc'
    },
    numberBox:{
        flexDirection:'row',
    },
    leftBox:{
        flex:1
    },
    addBtn:{
        flexDirection:'row',
        alignItems:'center',
        borderBottomWidth:1,
        borderBottomColor:'#ccc',
        backgroundColor:'#aaa',
        height:40,
        paddingLeft:10,
        paddingRight:10
    }

});